package cn.bocai.pc.web.controller;


import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.bocai.pc.service.BcThumpicService;
import cn.bocai.pc.service.VariableService;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
/** 
 * @className: BcUploadController
 * @description: 上传图片
 * @date: 2015年06月26日 下午6:20:31
 * @explain :多种方法处理上图片
 * @修改人：
 * @修改时间：
 * @修改内容：
 */
@Controller
@RequestMapping(value ="/plupload")
public class PluploadController {
	@Autowired
	private BcThumpicService bcThumpicService;
	@Autowired
	private VariableService variableService;

	private static final int BUFFER_SIZE = 100 * 1024;
	private static final Logger logger = Logger.getLogger(PluploadController.class);
	
	@RequestMapping(value = "/")
	public String index(HttpServletRequest request) {
		return "upload";
	}

	/**
	 * 使用plupload批量上传图片
	 * @param file		文件对象
	 * @param name		文件名称
	 * @param chunk		数据块序号
	 * @param chunks	数据块总数
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value="/plupload.do",method=RequestMethod.POST)	
	public String plupload(@RequestParam MultipartFile file,String colourType,HttpServletRequest request,HttpServletResponse response, HttpSession session) throws IOException {
		String FileExist=variableService.selectVariable("PIC_FileExist");//获取图片服务器的图片上传地址 http://localhost:8081/thumb/
		String PicBigUrl=variableService.selectVariable("PIC_bigUrl");//获取图片服务器的图片存放磁盘目录 D:/picture
		String result="";
	        byte[] ftype = null;
			try {
				ftype = file.getBytes();
			} catch (IOException e) {
				e.printStackTrace();
			}
			String oriFName = file.getOriginalFilename();//获得上传图片的名称
			boolean variable=true;
			for(int i=0;i<oriFName.length();i++){  
	    		 boolean matches = oriFName.substring(i,i+1).matches("[\\u4e00-\\u9fa5]+");//监测是否有中文
	    		 if(matches){
	    			 variable=false;
	    			 break;  
	    		 }
	    	  }
			if(!variable){
				throw new RuntimeException("出现中文名称！");//出现中文的时候抛出异常，前台捕抓
			}else{
				String url=FileExist+colourType+"/"+oriFName;//http://localhost:8081/thumb/col/xxx.jsp
				//查看图片是否存在，存在就删除，
	 			String fileCheckout = bcThumpicService.fileCheckout(PicBigUrl+"/thumb/"+colourType+"/"+oriFName);
	 			//下面是使用jersey进行跨服务器上传图片的代码
	 			if("ok".equals(fileCheckout)){
	 				//创建图片上传的客户端
	 	 			Client client = Client.create();
	 	 			//指定图片的在图片服务器上的完整路径
	 	 			WebResource resource = client.resource(url);
	 	 			//把图片上传到图片服务器
	 	 			resource.put(String.class, ftype);
	 	 		   /* result = "{\"relativePath\":\"/thumb/"+colourType+"/"+oriFName+"\", \"path\":\""+FileExist+colourType+"/"+oriFName+"\"}";*/
	 	 			/*result = "{\"parameter1\":\"sucess\", \"parameter2\":\"ok\"}";*/
	 			}
			}
		return result;
	}
	
	
	/*private void appendFile(InputStream in, File destFile) {
		OutputStream out = null;
		try {
			// plupload 配置了chunk的时候新上传的文件append到文件末尾
			if (destFile.exists()) {
				out = new BufferedOutputStream(new FileOutputStream(destFile, true), BUFFER_SIZE); 
			} else {
				out = new BufferedOutputStream(new FileOutputStream(destFile),BUFFER_SIZE);
			}
			in = new BufferedInputStream(in, BUFFER_SIZE);
			
			int len = 0;
			byte[] buffer = new byte[BUFFER_SIZE];			
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {		
			try {
				if (null != in) {
					in.close();
				}
				if(null != out){
					out.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
	}*/
	
}
